package com.far.game.xiuzhen.gm.web.api.admin;


import cn.hutool.core.lang.Validator;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.far.game.xiuzhen.common.conf.AppConf;
import com.far.game.xiuzhen.common.database.entity.Partner;
import com.far.game.xiuzhen.common.database.entity.User;

import com.far.game.xiuzhen.common.database.entity.UserPartner;
import com.far.game.xiuzhen.common.database.entity.Vo.UserVo;
import com.far.game.xiuzhen.common.dto.Visitor;

import com.far.game.xiuzhen.common.utils.AppUtil;
import com.far.game.xiuzhen.common.utils.JWTUtil;
import com.far.game.xiuzhen.common.utils.JWTUtils;
import com.far.game.xiuzhen.gm.web.BaseController;

import com.far.game.xiuzhen.service.IUserPartnerService;
import com.far.game.xiuzhen.service.IUserService;
import com.far.tools.bean.BeanUtil;
import com.far.tools.encrypt.Md5;
import com.far.tools.net.http.ReqParamWrapper;
import com.far.tools.net.http.transfer.QueryColumn;
import com.far.tools.net.http.transfer.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mike
 * @Date 2022-07-15 00:26:39
 */
@ApiOperation(value = "用户层")
@RestController
@CrossOrigin
@RequestMapping(value = "/api/admin/user")
@Slf4j
@Api(tags = "用户管理")
public class UserController extends BaseController {


    @Autowired
    IUserService iUserService;


    @Autowired
    @Qualifier("userPartnerServiceImpl")
    private IUserPartnerService iUserPartnerService;


    /**
     * @param
     * @description:
     * @return: com.far.game.xiuzhen.common.dto.ResultData<java.lang.String>
     * @author mike/Fang.J/Q184377367
     * @date: 2022/7/15 2:08
     */
    @GetMapping(value = "getToken")
    public ResultData<Map<String, String>> rtrtrt() {
        Visitor visitor = new Visitor();
        visitor.setTid(1);
        visitor.setPasswd("123");
        visitor.setUserName("mike");
        String token = JWTUtil.getJwtKey(visitor);
        Map<String, String> tokenVal = new HashMap<>();
        tokenVal.put("token", token);
        //Visitor newv= JWTUtil.getTokenForVisitor(token);

        return ResultData.ok(tokenVal);
    }

    @GetMapping(value = "test")
    public ResultData<String> test() {
        Visitor visitor = this.getVisitor();
        return ResultData.ok("okok");
    }


    @ApiOperation(value = "用户登录", notes = "只需要账号密码")
    @PostMapping(value = "login")
    public ResultData<Map<String, String>> login(@RequestBody User user) {

        String pass = Md5.val(AppConf.passHash + user.getPasswd());
        User findUser = iUserService.lambdaQuery().eq(User::getUserName, user.getUserName()).eq(User::getPasswd, pass).one();
        if (ObjectUtil.isEmpty(findUser)) {
            return ResultData.error("账号或密码错误");
        }
        if (findUser.getState() == 1) {
            return ResultData.error("账号已被禁用");
        }
        if (findUser.getType().equals(3)||findUser.getType().equals(null)) {
            return ResultData.error("账号权限不够");
        }

        Visitor visitor = BeanUtil.copyProperties(findUser, Visitor::new);
        //有账号，生成Token
        Map<String, String> tokenVal = new HashMap<>();
        tokenVal.put("token", JWTUtil.getJwtKey(visitor));
        return ResultData.ok(tokenVal);
    }

    /**
     * @param user
     * @description:修改用户信息
     * @return: com.far.game.xiuzhen.common.dto.ResultData<java.lang.String>
     * @author mike/Fang.J/Q184377367
     * @date: 2022/7/17 18:34
     */
    @ApiOperation(value = "修改用户信息", notes = "传入修改信息")
    @PostMapping(value = "save")
    public ResultData<String> save(@RequestBody User user) {

//        if (!Validator.isGeneral(user.getPasswd(), 8, 15)) {
//            return ResultData.error("密码长度只能介于8和16之间,且需要包含一个数字或者一个下划线");
//        }

        if (iUserService.save(user)) {
            return ResultData.ok("修改成功");
        } else {
            return ResultData.ok("修改失败");
        }
    }

    @ApiOperation(value = "添加用户", notes = "仅后台能调用此接口")
    @PostMapping(value = "add")
    public ResultData<String> add(@RequestBody User user) {
        //先手写验证吧
        if (ObjectUtil.isEmpty(user.getUserName()) || ObjectUtil.isEmpty(user.getPasswd()) || ObjectUtil.isEmpty(user.getPhone())) {
            return ResultData.error("账号,密码，手机号，都不能为空！");
        }


        if (!Validator.isMatchRegex("^[a-zA-Z0-9]*", user.getUserName())) {
            return ResultData.error("账号只能由字母和数字组成");
        }


        if (user.getUserName().length() < 4 || user.getUserName().length() > 15) {
            return ResultData.error("账号长度只能介于4和16之间");
        }

        if (!Validator.isGeneral(user.getPasswd(), 8, 15)) {
            return ResultData.error("密码长度只能介于8和16之间,且需要包含一个数字或者一个下划线");
        }

//
//        if (!Validator.isMatchRegex(Validator.MOBILE,user.getPhone())) {
//            return ResultData.error("手机号只能是11位，且必须都是数字");
//        }

        //查找是否有这个用户

        User findUser = iUserService.lambdaQuery().eq(User::getUserName, user.getUserName()).one();
        if (ObjectUtil.isNotEmpty(findUser)) {
            return ResultData.error("该账号已存在");
        }

        User regUser = new User();
        regUser.setUserName(user.getUserName());
        regUser.setPasswd(Md5.val(AppConf.passHash + user.getPasswd()));
        regUser.setState(user.getState());
        regUser.setPower(user.getPower());
        iUserService.getBaseMapper().insert(regUser);
        return ResultData.ok("添加成功");
    }

    @ApiOperation(value = "用户注册", notes = "账号，密码，手机号，游戏服务器，游戏区都是必填")
    @PostMapping(value = "reg")
    public ResultData<String> reg(@RequestBody User user) {


        //先手写验证吧
        if (ObjectUtil.isEmpty(user.getUserName()) || ObjectUtil.isEmpty(user.getPasswd()) || ObjectUtil.isEmpty(user.getPhone())) {
            return ResultData.error("账号,密码，手机号，都不能为空！");
        }


        if (!Validator.isMatchRegex("^[a-zA-Z0-9]*", user.getUserName())) {
            return ResultData.error("账号只能由字母和数字组成");
        }


        if (user.getUserName().length() < 4 || user.getUserName().length() > 15) {
            return ResultData.error("账号长度只能介于4和16之间");
        }

        if (!Validator.isGeneral(user.getPasswd(), 8, 15)) {
            return ResultData.error("密码长度只能介于8和16之间,且需要包含一个数字或者一个下划线");
        }


        if (!Validator.isMatchRegex(Validator.MOBILE, user.getPhone())) {
            return ResultData.error("手机号只能是11位，且必须都是数字");
        }

        //查找是否有这个用户

        User findUser = iUserService.lambdaQuery().eq(User::getUserName, user.getUserName()).one();
        if (ObjectUtil.isNotEmpty(findUser)) {
            return ResultData.error("该账号已注册");
        }


        User regUser = new User();
        regUser.setUserName(user.getUserName());
        regUser.setPasswd(Md5.val(AppConf.passHash + user.getPasswd()));
        regUser.setPhone(user.getPhone());
        regUser.setLastLoginTime(LocalDateTime.now());

        iUserService.getBaseMapper().insert(regUser);

        return ResultData.ok("注册成功");
    }

    /**
     * 用户表数据查询
     */
    @ApiOperation(value = "用户基础数据查询", notes = "ReqParamWrapper")
    @PostMapping(value = "user-query")
    private ResultData<IPage<User>> userQuery(@RequestBody ReqParamWrapper<User, String> reqParamWrapper) {

        User user = iUserService.lambdaQuery().eq(User::getUserName, getVisitor().getUserName()).one();
        if (ObjectUtil.isNull(user)) {
            return ResultData.error("未找到账号信息");
        }
        List<Integer> list = iUserService.getUserData(user);

        QueryColumn queryColumn = new QueryColumn();
        queryColumn.setName("tid");
        queryColumn.setFunc("in");
        queryColumn.setValue(list);
        reqParamWrapper.getColumns().add(queryColumn);
        IPage<User> iPage = reqParamWrapper.pageLists(iUserService);
        if (iPage.getRecords().size() == 0) {
            return ResultData.error("暂无数据");
        }
        return ResultData.ok(iPage);
    }

    /**
     * 用户表数据查询
     */
    @ApiOperation(value = "玩家账号数据查询", notes = "ReqParamWrapper")
    @PostMapping(value = "player-query")
    private ResultData<IPage<User>> playerQuery(@RequestBody ReqParamWrapper<User, String> reqParamWrapper) {

        User user = iUserService.lambdaQuery().eq(User::getUserName, getVisitor().getUserName()).one();
        if (ObjectUtil.isNull(user)) {
            return ResultData.error("未找到账号信息");
        }
        if (user.getType().equals(0) || user.getType().equals(1)) {
            QueryColumn queryColumn = new QueryColumn();
            queryColumn.setName("type");
            queryColumn.setFunc("in");
            queryColumn.setValue(3);
            reqParamWrapper.getColumns().add(queryColumn);
            IPage<User> page = reqParamWrapper.pageLists(iUserService);
            return ResultData.ok(page);
        } else if (user.getType().equals(2)) {
            if (ObjectUtil.isNull(user.getPower())) {
                return ResultData.error("未绑定权限");
            }
            List<UserPartner> userPartnerList = iUserPartnerService.lambdaQuery().in(UserPartner::getServerId, user.getPower()).list();

            List<Integer> list = userPartnerList.stream().map(UserPartner::getUserTid).distinct().collect(Collectors.toList());
            QueryColumn queryColumn = new QueryColumn();
            queryColumn.setName("tid");
            queryColumn.setFunc("in");
            queryColumn.setValue(list);
            reqParamWrapper.getColumns().add(queryColumn);
            IPage<User> page = reqParamWrapper.pageLists(iUserService);
            return ResultData.ok(page);
        }
        IPage<User> iPage = reqParamWrapper.pageLists(iUserService);
        if (iPage.getRecords().size() == 0) {
            return ResultData.error("暂无数据");
        }
        return ResultData.ok(iPage);
    }


//
//    /**
//     * 用户表数据删除
//     */
//    @ApiOperation(value = "用户表数据删除", notes = "删除用户表数据")
//    @ApiImplicitParam(name = "tid", value = "ID", required = true, paramType = "query", dataType = "Integer")
//    @GetMapping(value = "user-remove")
//    private ResultData<String> userRemove(@RequestParam("tid") Integer tid) {
//        UserPartner userPartner = iUserPartnerService.lambdaQuery().eq(UserPartner::getUserTid,tid).one();
//        if(ObjectUtil.isNotEmpty(userPartner)){
//            iUserPartnerService.removeById(userPartner.getTid());
//        }
//        if (iUserService.removeById(tid)) {
//            return ResultData.ok("删除成功");
//        }
//        return ResultData.error("删除失败");
//    }
//


    /**
     * @param userVo
     * @description:修改用户密码信息
     * @return: com.far.game.xiuzhen.common.dto.ResultData<java.lang.String>
     * @author mike/Fang.J/Q184377367
     * @date: 2022/7/17 18:34
     */
    @ApiOperation(value = "修改用户密码", notes = "传入修改密码")
    @PostMapping(value = "user-save")
    public ResultData<String> userSave(@RequestBody UserVo userVo) {

        if (!Validator.isGeneral(userVo.getPasswd(), 8, 15)) {
            return ResultData.error("密码长度只能介于8和16之间,且需要包含一个数字或者一个下划线");
        }
        User findUser = iUserService.lambdaQuery().eq(User::getTid, userVo.getTid()).one();
        String pass = Md5.val(AppConf.passHash + userVo.getWornPasswd());
        if (findUser.getPasswd().equals(pass)) {
            String password = Md5.val(AppConf.passHash + userVo.getPasswd());
            findUser.setPasswd(password);
            if (iUserService.updateById(findUser)) {
                return ResultData.ok("修改成功");
            } else {
                return ResultData.ok("修改失败");
            }
        } else {
            return ResultData.ok("旧密码输入错误! 请重新输入密码!");
        }

    }

    /**
     * 查询当前用户信息
     */
    @ApiOperation(value = "当前用户信息查询", notes = "ReqParamWrapper")
    @PostMapping(value = "get-user-query")
    private ResultData<User> getUserQuery() {

        User user = iUserService.lambdaQuery().eq(User::getUserName, getVisitor().getUserName()).one();
        if (ObjectUtil.isNull(user)) {
            return ResultData.error("未找到账号信息");
        }
        return ResultData.ok(user);
    }

    /**
     * 重置用户密码
     */
    @ApiOperation(value = "重设密码", notes = "ReqParamWrapper")
    @PostMapping(value = "reset-user-passwd")
    private ResultData<String> resetUserPasswd(@RequestBody User user) {

       User user1 = iUserService.lambdaQuery().eq(User::getTid,user.getTid()).one();
       if(ObjectUtil.isNull(user1)){
           return ResultData.ok("未找到账号");
       }

        if (!Validator.isGeneral(user.getPasswd(), 8, 15)) {
            return ResultData.error("密码长度只能介于8和16之间,且需要包含一个数字或者一个下划线");
        }

        String pass = Md5.val(AppConf.passHash + user.getPasswd());
            user1.setPasswd(pass);
        if (iUserService.updateById(user1)) {
            return ResultData.ok("重设成功");
        } else {
            return ResultData.ok("重设失败");
        }
    }


}
